package com.lu.aio;

import cn.hutool.core.util.CharsetUtil;
import com.lu.aio.client.AioClient;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.SocketChannel;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-10 17:12:00
 */
public class ChannelHandler {

    private AsynchronousSocketChannel channel;
    private String charset;

    public ChannelHandler(AsynchronousSocketChannel channel, String charset) {
        this.channel = channel;
        this.charset = charset;
    }

    public void writeAndFlush(Object msg){
        try {
            byte[] bytes = msg.toString().getBytes(charset);
            ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer buffer) {
                    //如果没有发送完成，继续发送
                    if(buffer.hasRemaining()){
                        channel.write(buffer, buffer, this);
                    }
                }
                @Override
                public void failed(Throwable exc, ByteBuffer buffer) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public AsynchronousSocketChannel channel(){
        return this.channel;
    }

    public void setChannel(AsynchronousSocketChannel channel){
        this.channel = channel;
    }

}
